package com.jsh.erp.service.attachment;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.AttachmentMapperEx;
import com.jsh.erp.datasource.mappers.MaterialMapperEx;
import com.jsh.erp.datasource.mappers.AttachmentMapper;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AttachmentService {
    private Logger logger = LoggerFactory.getLogger(AttachmentService.class);

    @Resource
    private AttachmentMapper attachmentMapper;
    @Resource
    private AttachmentMapperEx attachmentMapperEx;
    @Resource
    private LogService logService;
    @Resource
    private UserService userService;
    @Resource
    private SystemConfigService systemConfigService;

    public Attachment getAttachment(String id)throws Exception {
        Attachment result=null;
        try{
            result=attachmentMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<Attachment> getAttachmentListByIds(String ids)throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        List<Attachment> list = new ArrayList<>();
        try{
            AttachmentExample example = new AttachmentExample();
            example.createCriteria().andIdIn(idList);
            list = attachmentMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<Attachment> getAttachment()throws Exception {
        AttachmentExample example = new AttachmentExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Attachment> list=null;
        try{
            list=attachmentMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<Attachment> select(String name, int offset, int rows)throws Exception {
        List<Attachment> list=null;
        try{
//            list=attachmentMapperEx.selectByConditionAttachment(name, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public Long countAttachment(String name)throws Exception {
        Long result=null;
        try{
//            result=attachmentMapperEx.countsByAttachment(name);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertAttachment(JSONObject obj, HttpServletRequest request)throws Exception {
        Attachment attachment = JSONObject.parseObject(obj.toJSONString(), Attachment.class);
        attachment.setUploadFlag("0");
        int result=0;
        try{
            result=attachmentMapper.insertSelective(attachment);
            logService.insertLog("附件",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(attachment.getFileName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateAttachment(JSONObject obj, HttpServletRequest request)throws Exception {
        Attachment attachment = JSONObject.parseObject(obj.toJSONString(), Attachment.class);
        attachment.setUploadFlag("0");
        int result=0;
        try{
            result=attachmentMapper.updateByPrimaryKeySelective(attachment);
            logService.insertLog("附件",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(attachment.getFileName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }



    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteAttachment(String id, HttpServletRequest request)throws Exception {
        return batchDeleteAttachmentByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteAttachment(String ids, HttpServletRequest request) throws Exception{
        return batchDeleteAttachmentByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteAttachmentByIds(String ids)throws Exception {
        int result=0;

        return result;
    }

     public int checkIsNameExist(String id, String name) throws Exception{
        AttachmentExample example = new AttachmentExample();
        example.createCriteria().andIdNotEqualTo(id).andFileNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<Attachment> list=null;
        try{
            list=attachmentMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list==null?0:list.size();
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void deleteAttachmentHeaderId(String headerId)throws Exception {
        try{
            User userInfo=userService.getCurrentUser();
            String [] headerIdArray=headerId.split(",");
            attachmentMapperEx.batchDeleteAttachmentByHeadId(new Date(),userInfo==null?null:userInfo.getId(),headerIdArray);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertAttachmentWithObj(Attachment attachment)throws Exception {
        attachment.setUploadFlag("0");
        int result=0;
        try{
            result = attachmentMapper.insertSelective(attachment);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void saveAttachment(String attachment,String headerId, HttpServletRequest request)throws Exception {
        deleteAttachmentHeaderId(headerId);
        JSONArray rowArr = JSONArray.parseArray(attachment);
        if (null != rowArr && rowArr.size()>0) {
            for (int i = 0; i < rowArr.size(); i++) {
                Attachment attachmentVo = new Attachment();
                attachmentVo.setHeaderId(headerId);
                attachmentVo.setId(IdUtils.getUUID());
                JSONObject tempInsertedJson = JSONObject.parseObject(rowArr.getString(i));
                if (tempInsertedJson.get("fileName") != null && !tempInsertedJson.get("fileName").equals("")) {
                    attachmentVo.setFileName(tempInsertedJson.getString("fileName"));
                }
                if (tempInsertedJson.get("data") != null && !tempInsertedJson.get("data").equals("")) {
                    attachmentVo.setData(tempInsertedJson.getString("data"));
                }
                if (tempInsertedJson.get("type") != null && !tempInsertedJson.get("type").equals("")) {
                    attachmentVo.setType(tempInsertedJson.getString("type"));
                }
                this.insertAttachmentWithObj(attachmentVo);
            }
        }
    }
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void saveMaterialAttachment(JSONObject obj,String headerId, HttpServletRequest request)throws Exception {
        deleteAttachmentHeaderId(headerId);
        JSONArray rowArr = obj.getJSONArray("attachment");
        if (null != rowArr && rowArr.size()>0) {
            for (int i = 0; i < rowArr.size(); i++) {
                Attachment attachmentVo = new Attachment();
                attachmentVo.setHeaderId(headerId);
                attachmentVo.setId(IdUtils.getUUID());
                JSONObject tempInsertedJson = JSONObject.parseObject(rowArr.getString(i));
                if (tempInsertedJson.get("fileName") != null && !tempInsertedJson.get("fileName").equals("")) {
                    attachmentVo.setFileName(tempInsertedJson.getString("fileName"));
                }
                if (tempInsertedJson.get("data") != null && !tempInsertedJson.get("data").equals("")) {
                    attachmentVo.setData(tempInsertedJson.getString("data"));
                }
                if (tempInsertedJson.get("type") != null && !tempInsertedJson.get("type").equals("")) {
                    attachmentVo.setType(tempInsertedJson.getString("type"));
                }
                this.insertAttachmentWithObj(attachmentVo);
            }
        }
    }

    public List<Attachment> getAttachmentListById(String id)throws Exception {
        List<Attachment> list=null;
        try{
            AttachmentExample example = new AttachmentExample();
            example.createCriteria().andHeaderIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = attachmentMapper.selectByExampleWithBLOBs(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public String getAttachmentById(String id)throws Exception {
        List<Attachment> list=null;
        String data=null;
        try{
            AttachmentExample example = new AttachmentExample();
            example.createCriteria().andHeaderIdEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = attachmentMapper.selectByExampleWithBLOBs(example);
            if (null != list && list.size()>0){
                Attachment attachment = list.get(0);
                data=attachment.getData();
            }
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return data;
    }
}
